package com.xinzhi.service.impl;

import com.xinzhi.config.MD5Utils;
import com.xinzhi.dao.LoginUserDao;
import com.xinzhi.pojo.CardNumber;
import com.xinzhi.pojo.User;
import com.xinzhi.service.IInsertService;
import com.xinzhi.service.ILoginUserService;
import com.xinzhi.utils.JwtUtil;
import com.xinzhi.utils.RedisUtils;
import com.xinzhi.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class LoginUserServiceImpl implements ILoginUserService {
    @Autowired
    private LoginUserDao loginUserDao;

    @Autowired
    @Qualifier("insertServiceImpl")
    private IInsertService insertService;

    private static final String REDIS_TOKEN_PREFIX = "USER_TOKEN_";
    private static final long TOKEN_EXPIRATION = 300; // 5 minutes

    @Override
    public Result login(String phone, String password) {
        if (phone == null) {
            return Result.error("手机号不能为空");
        }
        if (password == null) {
            return Result.error("密码不能为空");
        }
        if (!phone.matches("^(?:(?:\\+|00)86)?1\\d{10}$")) {
            return Result.error("手机号格式不正确");
        }
        if (!password.matches("^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d]{8,20}$")) {
            return Result.error("密码格式不正确");
        }
        String pwd = MD5Utils.MD5Upper(password);
        User user = loginUserDao.login(phone);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!user.getPassword().equals(pwd)) {
            return Result.error("密码输入错误");
        }
        updateLoginTime(phone);

        // 生成JWT token
        String token = JwtUtil.createJWT(user.getId().toString(), phone, TOKEN_EXPIRATION * 1000L);

        // 将 token 存储到 Redis 中
        RedisUtils.set(REDIS_TOKEN_PREFIX + phone, token, TOKEN_EXPIRATION);

        return Result.ok("登录成功").put("token", token);
    }

    @Override
    public Result loginCode(String phone, String code) {
        if (phone == null) {
            return Result.error("手机号不能为空");
        }
        if (!phone.matches("^(?:(?:\\+|00)86)?1\\d{10}$")) {
            return Result.error("手机号格式不正确");
        }
        Result result = insertService.sendVerificationCode(phone);
        System.out.println(result);
        Result result1 = insertService.verifyCode(phone, code);
        System.out.println(result1);
        updateLoginTime(phone);
        User user = new User();

        // 生成JWT token
        String token = JwtUtil.createJWT(user.getId().toString(), phone, TOKEN_EXPIRATION * 1000L);

        // 将 token 存储到 Redis 中
        RedisUtils.set(REDIS_TOKEN_PREFIX + phone, token, TOKEN_EXPIRATION);

        return Result.ok("登录成功").put("token", token);
    }

    @Override
    public Result updateLoginTime(String phone) {
        LocalDateTime localDateTime = LocalDateTime.now();
        int i = loginUserDao.updateLoginTime(phone, localDateTime);
        if (i == 0) {
            return Result.error("更新失败");
        }
        return Result.ok("更新成功");
    }

    /**
     * 绑定银行卡
     * @param cardNumber
     * @return
     */
    @Override
    public Result insertIdCard(CardNumber cardNumber) {
        if (cardNumber.getPhone() == null) {
            return Result.error("手机号不能为空");
        }
        if (cardNumber.getCardNumber() == null) {
            return Result.error("银行卡号不能为空");
        }
        if (!cardNumber.getPhone().matches("^(?:(?:\\+|00)86)?1\\d{10}$")) {
            return Result.error("手机号格式不正确");
        }
        if (!cardNumber.getCardNumber().matches("^\\d{16,19}$")) {
            return Result.error("银行卡号格式不正确");
        }
        List<CardNumber> cardNumbers = loginUserDao.selectCardNumber(cardNumber.getPhone());
        for (CardNumber cardNumber1 : cardNumbers) {
            if (cardNumber1.getCardNumber().equals(cardNumber.getCardNumber())) {
                return Result.error("该银行卡号已绑定");
            }
        }
        int i = loginUserDao.insertIdCard(cardNumber);
        return i > 0 ? Result.ok("绑定成功") : Result.error("绑定失败");
    }
}
